import axios from './axios';
import { stringifyUserPermissions } from '../utils/routePermission';

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

// 用户信息接口
export interface User {
  uid?: number;
  user: string;
  name: string;
  mobile?: string;
  is_active?: "1" | "0";
  user_perm: string;
  level: number;
  createTime?: string;
  lastLoginTime?: string;
  status?: 'active' | 'inactive';
}

// 添加用户参数
export interface AddUserParams {
  user: string;
  password: string;
  passwordv: string;
  name: string;
  mobile?: string;
  is_active?: "1" | "0";
  user_perm: string;
  level: number;
}

// 修改用户参数
export interface UpdateUserParams {
  uid: number;
  name: string;
  mobile?: string;
  is_active?: "1" | "0";
  user_perm: string;
  level: number;
}

// 获取用户列表参数
export interface GetUsersParams {
  page: number;
  ps: number;
  key?: string;
  cbt?: string; // 创建开始时间
  cet?: string; // 创建结束时间
  lbt?: string; // 登录开始时间
  let?: string; // 登录结束时间
  level?: number; // 等级筛选
  is_active?: "1" | "0"; // 状态筛选
}

// 修改密码参数
export interface UpdatePasswordParams {
  password: string;
  passwordv: string;
}

// API响应格式
export interface ApiResponse<T = any> {
  code: number;
  message: string;
  data?: T;
}

// 用户列表响应
export interface UsersListResponse {
  total: number;
  users: User[];
}

// 获取Token（从localStorage或其他地方）
const getToken = (): string => {
  return localStorage.getItem('token') || '';
};

// 添加用户
export const addUser = async (params: AddUserParams): Promise<ApiResponse> => {
  try {
    // 处理权限数据：如果是数组格式，转换为JSON字符串
    const processedParams = {
      ...params,
      user_perm: Array.isArray(params.user_perm) 
        ? stringifyUserPermissions({
            modules: params.user_perm as any,
            level: params.level as any
          })
        : params.user_perm
    };

    const response = await axios.post(
      `${API_BASE_URL}/-/bin.user_operate.add_user`,
      processedParams,
      {
        headers: {
          'token': getToken()
        }
      }
    );
    
    console.log('addUser API响应:', response.data); // 调试日志
    
    // 适配后端返回结构，code为200也视为成功，提示msg
    if (response.data && (response.data.code === 0 || response.data.code === 200)) {
      return {
        code: 0,
        message: response.data.msg || response.data.message || '添加成功',
        data: response.data.data
      };
    }
    return {
      code: response.data.code || -1,
      message: response.data.msg || response.data.message || '添加用户失败',
      data: response.data.data
    };
  } catch (error: any) {
    console.error('添加用户请求异常:', error);
    // 检查是否是HTTP错误响应
    if (error.response && error.response.data) {
      return {
        code: error.response.data.code || -1,
        message: error.response.data.msg || error.response.data.message || '添加用户失败',
        data: error.response.data.data
      };
    }
    throw new Error(error?.message || '网络请求失败');
  }
};

// 修改用户信息
export const updateUser = async (params: UpdateUserParams): Promise<ApiResponse> => {
  try {
    // 处理权限数据：如果是数组格式，转换为JSON字符串
    const processedParams = {
      ...params,
      user_perm: Array.isArray(params.user_perm) 
        ? stringifyUserPermissions({
            modules: params.user_perm as any,
            level: params.level as any
          })
        : params.user_perm
    };

    const response = await axios.post(
      `${API_BASE_URL}/-/bin.user_operate.update_user`,
      processedParams,
      {
        headers: {
          'token': getToken()
        }
      }
    );
    // 适配后端返回结构，code为0或200都视为成功，提示msg
    if (response.data && (response.data.code === 0 || response.data.code === 200)) {
      return {
        code: 0,
        message: response.data.msg || response.data.message || '修改成功',
        data: response.data.data
      };
    }
    return {
      code: response.data.code,
      message: response.data.msg || response.data.message || '修改用户信息失败',
      data: response.data.data
    };
  } catch (error) {
    console.error('修改用户信息失败:', error);
    throw new Error('修改用户信息失败');
  }
};

// 获取所有用户
export const getAllUsers = async (params: GetUsersParams): Promise<ApiResponse<UsersListResponse>> => {
  try {
    const response = await axios.post(
      `${API_BASE_URL}/-/bin.user_operate.get_all_user`,
      params,
      {
        headers: {
          'token': getToken()
        }
      }
    );
    // 适配后端新结构
    if (response.data && Array.isArray(response.data.data)) {
      const users = response.data.data.map((item: any) => ({
        uid: item.uid,
        user: item.user,
        name: item.name,
        mobile: item.mobile,
        is_active: item.is_active === '1' || item.is_active === 1 ? "1" : "0",
        user_perm: item.user_perm || JSON.stringify({modules: [], level: Number(item.level), created_at: new Date().toISOString()}), // 权限字段，支持JSON格式
        level: Number(item.level),
        createTime: item.ctime,
        lastLoginTime: item.utime,
        status: item.is_active === '1' ? 'active' : 'inactive'
      }));
      return {
        code: response.data.code === 200 ? 0 : response.data.code,
        message: '',
        data: {
          users,
          total: response.data.total
        }
      };
    }
    return {
      code: response.data.code,
      message: response.data.message || '获取用户列表失败',
      data: { users: [], total: 0 }
    };
  } catch (error) {
    console.error('获取用户列表失败:', error);
    throw new Error('获取用户列表失败');
  }
};

// 修改密码
export const updatePassword = async (params: UpdatePasswordParams): Promise<ApiResponse> => {
  try {
    const response = await axios.post(
      `${API_BASE_URL}/-/bin.user_operate.update_password`,
      params,
      {
        headers: {
          'token': getToken()
        }
      }
    );
    // 适配后端返回结构，code为302也视为成功，提示msg
    if (response.data && (response.data.code === 0 || response.data.code === 302)) {
      return {
        code: 0,
        message: response.data.msg || response.data.message || '修改成功',
        data: response.data.data
      };
    }
    return {
      code: response.data.code,
      message: response.data.msg || response.data.message || '修改密码失败',
      data: response.data.data
    };
  } catch (error) {
    console.error('修改密码失败:', error);
    throw new Error('修改密码失败');
  }
}; 